import BaseView from "../baseView.js";

export default class AddStudentView extends BaseView {

    constructor(){
      super();
      this.init();
    }


    render(){
        $("#showContent").html(
            `
            <h1>添加学生</h1>
            <hr/>
            <form class="layui-form" >
  <div class="layui-form-item">
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-inline">
      <input type="text" id="name" required  lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">年龄</label>
    <div class="layui-input-inline">
      <input type="text" id="age" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">地址：</label>
    <div class="layui-input-inline">    
      <select id="city" lay-verify="required">
        <option value="成都市">成都市</option>
        <option value="德阳市">德阳市</option>
        <option value="自贡市">自贡市</option>
        <option value="攀枝花市">攀枝花市</option>
      </select>
    </div>
  </div>
  
 
  <div class="layui-form-item">
    <label class="layui-form-label">性别</label>
    <div class="layui-input-block">
      <input type="radio" name="sex" value="男" title="男">
      <input type="radio" name="sex" value="女" title="女" checked>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button type='button' id='addBtn' class="layui-btn" lay-submit lay-filter="formDemo">添加</button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>
</form>  `
        )
     }

    handle(){

        //重新渲染表单form
        layui.use('form', function(){
            var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    
            //如果你的 HTML 是动态生成的，自动渲染就会失效
            //因此你需要在相应的地方，执行下述方法来进行渲染
            form.render();//(******注意)
            $("#addBtn").click(()=>{
                $.ajax({
                    type:"post",
                    url:"/api/student/addstudent",
                    data:{
                        name:$('#name').val(),
                        age:$('#age').val(),
                        gender:$('input:checked').val(),
                        address: $('#city').val()
                    },
                    dataType:"json",
                    success:(data)=>{
                      //console.log(data);
                      if(data.code==0){
                         alert(data.msg);
                         //跳转到学生数据页面
                        window.location.href="#/main/studentlist"   
                      }else{
                        alert(data.msg)
                      }
                    }
                })
            })
          });  
    } 
}